//
//  MovieViewController.m
//  豆瓣
//
//  Created by dllo on 15/12/7.
//  Copyright © 2015年 dllo. All rights reserved.
//

#import "MovieViewController.h"
#import "MovieTableViewCell.h"
#import "Movie.h"
#import "MovieDetailViewController.h"
#import "AFNetworking.h"
#import "MovieGridView.h"
#import "UIImageView+WebCache.h"
#import "DataBaseSingleton.h"

@interface MovieViewController ()<UITableViewDataSource, UITableViewDelegate, MovieGridViewDelegate>

@property (nonatomic, retain) UITableView *myTableView;
@property (nonatomic, retain) NSMutableArray *allArray;
@property (nonatomic, retain) UIScrollView *myScrollView;


@end

@implementation MovieViewController

- (void)dealloc{
    [_myScrollView release];
    [_allArray release];
    [_myTableView release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    // 创建mycollection数据库表
    [[DataBaseSingleton shareDataBase] createTable];
    
    
    self.navigationItem.title = @"电影";
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self afnGetRequest];
    
    self.myTableView = [[UITableView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    [self.view addSubview:_myTableView];
    
//    UINib *nib = [UINib nibWithNibName:@"MovieTableViewCell" bundle:[NSBundle mainBundle]];
//    [self.myTableView registerNib:nib forCellReuseIdentifier:@"cell"];
    
    
    [self.myTableView registerClass:[MovieTableViewCell class] forCellReuseIdentifier:@"cell"];
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    [_myTableView release];
    
    
    UIImage *image = [[UIImage imageNamed:@"btn_nav_list"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:image style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonAction:)];
    
    self.allArray = [NSMutableArray array];

    
  
//    
//    [AppTools getDataFromJsonWithFileName:@"http://project.lanou3g.com/teacher/yihuiyun/lanouproject/movielist.php" Block:^(id result) {
//        NSMutableDictionary *dic = result;
//        
//        
////        NSLog(@"++++++++%@", dic);
//        NSMutableArray *array = [dic objectForKey:@"result"];
//        for (NSDictionary *dic in array) {
//            Movie *movie = [[Movie alloc] init];
//            [movie setValuesForKeysWithDictionary:dic];
////            NSLog(@"%@", dic);
//            [self.allArray addObject:movie];
//            [movie release];
////            NSLog(@"%@", movie.movieName);
//            
////            NSLog(@"是否是主线程 === %d",[NSThread isMainThread]);
//            //下面的方法是回到主线程
//            dispatch_async(dispatch_get_main_queue(), ^{
//                
////                NSLog(@"是否是主线程22 === %d",[NSThread isMainThread]);
//                
//                [self.myTableView reloadData];
//                
//            });
//
//        }
//        
//        
//    } error:^(NSError *error) {
//        
//        
//        
//    }];
    
    
}

- (void)rightBarButtonAction:(UIBarButtonItem *)batBtn{
    
    UIImage *TwoRightImage = [[UIImage imageNamed:@"btn_nav_list"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithImage:TwoRightImage style:UIBarButtonItemStyleDone target:self action:@selector(TwoRightBarButtonItemAction:)] autorelease];
    
    self.myScrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
    self.myScrollView.backgroundColor = [UIColor whiteColor];
//    NSLog(@"asddfsj %ld", self.allArray.count);
    for (int i = 0; i < self.allArray.count; i++) {
        MovieGridView *movieGridView = [[MovieGridView alloc] initWithFrame: CGRectMake(10 + (i % 3) * ( 335 / 3 + 10), 20 + (i / 3) * (10 + 150 + 20), 335 / 3, 150)];
        
        [movieGridView.movieGridImageView sd_setImageWithURL:[NSURL URLWithString:((Movie *)self.allArray[i]).pic_url] placeholderImage:[UIImage imageNamed:@"picholder"]];
        movieGridView.nameLabel.text = ((Movie *)self.allArray[i]).movieName;
        [self.myScrollView addSubview:movieGridView];
        [movieGridView release];
        movieGridView.movieGridImageView.tag = 1000 + i;
        movieGridView.myDelegate = self;
        
        
    }
    self.myScrollView.contentSize = CGSizeMake(0, 10 + (150 + 20) * (self.allArray.count + 2) / 3 + 40);
    
    [self.view addSubview:_myScrollView];
    [_myScrollView release];
    
}

- (void)TwoRightBarButtonItemAction:(UIButton *)button{
    [self.view sendSubviewToBack:self.myScrollView];
    UIImage *image = [[UIImage imageNamed:@"btn_nav_collection"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:image style:UIBarButtonItemStylePlain target:self action:@selector(OneRightButtonAction:)];
    
    
}

- (void)OneRightButtonAction:(UIBarButtonItem *)button{
    [self rightBarButtonAction:button];
}


- (void)didSelectMovieGridView:(MovieGridView *)ypView IndexPath:(NSIndexPath *)indexPath{
    MovieDetailViewController *movieDetailVC = [[MovieDetailViewController alloc] init];
    movieDetailVC.movie = [self.allArray objectAtIndex:indexPath.row];
    movieDetailVC.movieId = movieDetailVC.movie.movieId;

    [self.navigationController pushViewController:movieDetailVC animated:YES];
    
    [movieDetailVC release];
    
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    MovieTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    Movie *movie = [self.allArray objectAtIndex:indexPath.row];
    cell.movie = movie;
//    NSLog(@"!!()*)(*)(*)(*)(*");
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.allArray.count;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 170;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    MovieDetailViewController *movieDetailVC = [[MovieDetailViewController alloc] init];
    movieDetailVC.movie = [self.allArray objectAtIndex:indexPath.row];
    movieDetailVC.movieId = movieDetailVC.movie.movieId;
    [self.navigationController pushViewController:movieDetailVC animated:YES];

    [movieDetailVC release];
}



-(void)afnGetRequest
{
    
//    AFNetworkReachabilityManager *netWorkManager = [AFNetworkReachabilityManager sharedManager];
//    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
//    
//    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
//        
//        NSLog(@"网络状态 = %ld", status);
//    }];
    
    
    
    NSString *url_string = [NSString stringWithFormat:@"http://project.lanou3g.com/teacher/yihuiyun/lanouproject/movielist.php"];
    
    
    //[NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];  代表支持所有的接口类型
    //请求管理者 所有的网络请求,均有manager发起
    AFHTTPRequestOperationManager* manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    [manager GET:url_string parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
//        [netWorkManager stopMonitoring];
        
        
        NSLog(@"使用AFN进行get请求 ===  %@",responseObject);
        NSDictionary *dic = responseObject;
        
        
//                NSLog(@"++++++++%@", dic);
                NSMutableArray *array = [dic objectForKey:@"result"];
                for (NSDictionary *dic in array) {
                    Movie *movie = [[Movie alloc] init];
                    [movie setValuesForKeysWithDictionary:dic];
        //            NSLog(@"%@", dic);
                    [self.allArray addObject:movie];
                    [movie release];
//                    NSLog(@"%@", movie.movieName);
        
        //            NSLog(@"是否是主线程 === %d",[NSThread isMainThread]);
                    //下面的方法是回到主线程
                    dispatch_async(dispatch_get_main_queue(), ^{
        
        //                NSLog(@"是否是主线程22 === %d",[NSThread isMainThread]);
                
                        [self.myTableView reloadData];
                    });
        
                }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                    
        NSLog(@"失败==== %@",error);
            
    }];
        
        
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
